package com.ld.common.util;

import java.util.ArrayList;
import java.util.List;

import com.ld.common.util.security.ProjectSecurityUtil;
import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.encryptor.BlowfishEncryptor;

public class PassUtil {
    public static final List<String> WEAK_PASSWORDS = new ArrayList<>(); // 弱口令
    // 密钥，建议根据不同的业务添加不同的密钥，防止一个密钥泄露造成的数据不安全
    public static final String PASS_KEY = ProjectSecurityUtil.getSecurityKey().getPassKey();
    public static final BlowfishEncryptor BFISH = new BlowfishEncryptor(PASS_KEY);

    // 初始化弱口令
    static {
        WEAK_PASSWORDS.add("^(.)\\1+$"); // 相同字符
        // 纯字母
        WEAK_PASSWORDS.add("admin");
        WEAK_PASSWORDS.add("manager");
        WEAK_PASSWORDS.add("tomcat");
        WEAK_PASSWORDS.add("jboss");
        WEAK_PASSWORDS.add("weblogic");
        // 纯数字
        WEAK_PASSWORDS.add("123456");
        WEAK_PASSWORDS.add("12345678");
        WEAK_PASSWORDS.add("1314520");
        WEAK_PASSWORDS.add("1314521");
        WEAK_PASSWORDS.add("123123");
        WEAK_PASSWORDS.add("112233");
        WEAK_PASSWORDS.add("5201314");
        WEAK_PASSWORDS.add("7758521");
        WEAK_PASSWORDS.add("1123581321");
        // 数字+字母
        WEAK_PASSWORDS.add("admin123");
        WEAK_PASSWORDS.add("123456abc");
        WEAK_PASSWORDS.add("123qwe");
        WEAK_PASSWORDS.add("a123123");
        WEAK_PASSWORDS.add("root123");
        WEAK_PASSWORDS.add("woaini1314");
    }

    /**
     * 加密
     * 
     * @param pass
     * @return
     */
    public static String encryptPass(String pass) {
        return BFISH.encrypt(pass);
    }

    /**
     * 解密
     * 
     * @param pass
     * @return
     */
    public static String decryptPass(String pass) {
        return BFISH.decrypt(pass);
    }

    public static void main(String[] args) {
        String pass = encryptPass("123456");
        System.out.println(pass + " " + decryptPass(pass));
        System.out.println(pass + " " + checkPwdSimple("123456"));
    }

    /**
     * 检验密码是否过于简单
     * 
     * @Title checkPwdSimple
     * @author 吕凯
     * @date 2016年4月12日 下午2:52:39
     * @param newpwd
     * @return boolean
     */
    public static boolean checkPwdSimple(String newpwd) {
        if (newpwd == null) {
            return true;
        }
        if (ListUtils.isNotEmpty(WEAK_PASSWORDS)) {
            return WEAK_PASSWORDS.stream().anyMatch(str -> newpwd.matches(str));
        }
        return false;
    }

}
